package xgenerator.util;

import java.io.Closeable;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class ResourceContext {
	
	public static void main(String[] args) {
		System.out.println(ResourceContext.Resource.class);
		System.out.println(ResourceContext.ResourceFactory.class);
		System.out.println(ResourceContext.ResourceHolder.class);
		System.out.println(ResourceContext.getContext().currentResource());
		System.out.println(ResourceContext.getContext().currentResource());
		System.out.println(ResourceContext.getContext().currentResource().getName().hashCode());
		System.out.println(ResourceContext.getContext().currentResource().getName().hashCode());
	}
	
	private static final Map<String, ResourceContext> CONTEXT_MAP = Collections.synchronizedMap(new HashMap<String, ResourceContext>());
	
	/**
	 * connectionHolder
	 */
	private ThreadLocal<Resource> resourceHolder;

	private ResourceContext() {
		this.resourceHolder = new ResourceHolder<Resource>();
	}
	
	public static final ResourceContext getContext() {
		String currentThreadName = Thread.currentThread().getName();
		ResourceContext context = CONTEXT_MAP.get(currentThreadName);
		if(null == context) {
			context = new ResourceContext();
			CONTEXT_MAP.put(currentThreadName, context);
		}
		return context;
	}
	
	public Resource currentResource() {
		return this.resourceHolder.get();
	}
	
	public interface Resource extends Closeable {
		public String getName();
	}
	
	private class ResourceFactory {
		public Resource getResource() {
			return new Resource() {
				public String getName() {
					return "MyResource";
				}

				public void close() throws IOException {
					
				}
			};
		}
	}
	
	private class ResourceHolder<T extends Resource> extends ThreadLocal<Resource> {
		
		private ResourceFactory resourceFactory;
		
		public ResourceHolder() {
			this.resourceFactory = new ResourceFactory();
		}
		
		@Override
		protected Resource initialValue() {
			return this.resourceFactory.getResource();
		}
	}
}
